from sqlalchemy.orm import Session
from app.core.database import SessionLocal, engine, Base
from app.core.security import get_password_hash
from app.core.config import settings
from app.models import *
from decimal import Decimal
import json

def init_database():
    Base.metadata.create_all(bind=engine)
    db = SessionLocal()
    
    try:
        admin_user = db.query(User).filter(User.username == settings.ADMIN_USERNAME).first()
        if not admin_user:
            admin_user = User(
                username=settings.ADMIN_USERNAME,
                password_hash=get_password_hash(settings.ADMIN_PASSWORD),
                phone="13800138000",
                role=UserRole.ADMIN
            )
            db.add(admin_user)
            print(f"创建管理员账号: {settings.ADMIN_USERNAME}")
        
        apartment_a = db.query(ApartmentType).filter(ApartmentType.type_code == "A").first()
        if not apartment_a:
            apartment_a = ApartmentType(
                type_code="A",
                type_name="A型户型",
                base_price=Decimal("2800"),
                description="标准A型户型，适合中小户型"
            )
            db.add(apartment_a)
            print("创建户型A配置")
        
        apartment_b = db.query(ApartmentType).filter(ApartmentType.type_code == "B").first()
        if not apartment_b:
            apartment_b = ApartmentType(
                type_code="B",
                type_name="B型户型",
                base_price=Decimal("3200"),
                description="标准B型户型，适合大户型"
            )
            db.add(apartment_b)
            print("创建户型B配置")
        
        price_rule_a = db.query(PriceRule).filter(
            PriceRule.apartment_type == "A"
        ).first()
        if not price_rule_a:
            price_rule_a = PriceRule(
                apartment_type="A",
                area_min=Decimal("30"),
                area_max=Decimal("60"),
                unit_price=Decimal("2800"),
                description="A型户型标准造价",
                is_active=True
            )
            db.add(price_rule_a)
            print("创建造价规则A")
        
        price_rule_b = db.query(PriceRule).filter(
            PriceRule.apartment_type == "B"
        ).first()
        if not price_rule_b:
            price_rule_b = PriceRule(
                apartment_type="B",
                area_min=Decimal("50"),
                area_max=Decimal("80"),
                unit_price=Decimal("3200"),
                description="B型户型标准造价",
                is_active=True
            )
            db.add(price_rule_b)
            print("创建造价规则B")
        
        member_discount_config = db.query(SystemConfig).filter(
            SystemConfig.config_key == "member_discount"
        ).first()
        if not member_discount_config:
            member_discount_config = SystemConfig(
                config_key="member_discount",
                config_value="500",
                config_type="decimal",
                description="会员优惠金额"
            )
            db.add(member_discount_config)
            print("创建会员优惠配置")
        
        config_a = db.query(SystemConfig).filter(
            SystemConfig.config_key == "configuration_A"
        ).first()
        if not config_a:
            config_items = [
                "钢结构夹层框架",
                "楼梯定制安装",
                "地面找平处理",
                "墙面基础处理",
                "水电预留接口"
            ]
            config_a = SystemConfig(
                config_key="configuration_A",
                config_value=json.dumps(config_items, ensure_ascii=False),
                config_type="json",
                description="A型户型标准配置清单"
            )
            db.add(config_a)
            print("创建A型配置清单")
        
        config_b = db.query(SystemConfig).filter(
            SystemConfig.config_key == "configuration_B"
        ).first()
        if not config_b:
            config_items = [
                "加强型钢结构夹层框架",
                "定制钢木结构楼梯",
                "地面找平及防水处理",
                "墙面基础处理及加固",
                "水电全套预留接口",
                "栏杆护栏安装"
            ]
            config_b = SystemConfig(
                config_key="configuration_B",
                config_value=json.dumps(config_items, ensure_ascii=False),
                config_type="json",
                description="B型户型标准配置清单"
            )
            db.add(config_b)
            print("创建B型配置清单")
        
        db.commit()
        print("\n数据库初始化完成！")
        print(f"管理员账号: {settings.ADMIN_USERNAME}")
        print(f"管理员密码: {settings.ADMIN_PASSWORD}")
        
    except Exception as e:
        db.rollback()
        print(f"初始化失败: {str(e)}")
        raise
    finally:
        db.close()

if __name__ == "__main__":
    init_database()

